package com.mymarkdown.app.websocket;

import com.mymarkdown.app.common.ChainHandlerResult;
import com.mymarkdown.app.interfaces.UserInfoService;
import com.mymarkdown.app.websocket.enums.MessageTypeEnum;
import com.mymarkdown.app.websocket.handler.SelectiveMessageHandler;
import com.mymarkdown.app.websocket.interfaces.HandlerMessage;
import com.mymarkdown.app.util.CurrentUserUtil;
import com.mymarkdown.app.websocket.interfaces.WebSocketSendMessage;
import com.mymarkdown.app.websocket.message.MessagePojo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Objects;

/**
 * @author zenglun
 * @date 2021/12/5 11:08 上午
 * @description: 一个websocket服务器
 */
@Slf4j
@Component
@ServerEndpoint(value = "/myWs")
public class WebSocketServer {

    private HandlerMessage selectiveMessageHandler;

    private WebSocketSendMessage webSocketSendMessage;

    private UserInfoService userInfoService;

    public WebSocketServer(){
        //此处代码采用单例模式,websocket在bean对象在SpringBoot中以多列形式存在
        //以防空指针异常
        selectiveMessageHandler = SelectiveMessageHandler.getSelf();
        webSocketSendMessage = CurrentUserUtil.getSelf();
        userInfoService = CurrentUserUtil.getSelf();
    }

    /**
     * 客户端开始连接服务器
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        log.info("[WebSocketServer]---[onOpen],用户已经连接,Session为:{}", session);
        userInfoService.setSession(session);

    }

    /**
     * 服务器接受到客户端消息
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
        //读取到的字符信息写入文件
        //解析用户的信息
        ChainHandlerResult chainHandlerResult = selectiveMessageHandler.onMessage(message, session);
        boolean result = chainHandlerResult.isResult();
        if (!result && Objects.isNull(chainHandlerResult.getException())){
            log.error("[WebSocketServer]---[onMessage],处理发生异常,异常信息为:{}", chainHandlerResult.getException());
            webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.TISP_MSG.getMessageType()).setBody("处理发生异常!"));
        }
    }
}
